o2.xDesktop = o2.xDesktop || {};
o2.xd = o2.xDesktop;
o2.xDesktop.requireApp = function(module, clazz, callback, async){
    o2.requireApp(module, clazz, callback, async)
};
o2.xApplication = o2.xApplication || {};

MWF.xDesktop.loadConfig = function(callback){
    o2.JSON.get("res/config/config.json", function(config) {
        if (config.proxyCenterEnable){
            if (o2.typeOf(config.center)==="array"){
                config.center.forEach(function(c){
                    c.port = window.location.port;
                });
            }else{
                config.port = window.location.port;
            }
        }
        layout.config = config;
        if (layout.config.app_protocol === "auto") {
            layout.config.app_protocol = window.location.protocol;
        }
        layout.config.systemName = layout.config.systemName || layout.config.footer;
        layout.config.systemTitle = layout.config.systemTitle || layout.config.title;
        if (callback) callback();
    });
};
MWF.xDesktop.getService = function(callback) {
    MWF.xDesktop.getServiceAddress(layout.config, function(service, center){
        layout.serviceAddressList = service;
        layout.centerServer = center;
        if (callback) callback();
    });
};
MWF.xDesktop.loadService = function(callback){
    MWF.xDesktop.loadConfig(function(){
        MWF.xDesktop.getService(callback);
    });
};

MWF.xDesktop.checkLogin = function(loginFun){
    layout.authentication = new MWF.xDesktop.Authentication({
        "onLogin": loginFun
    });
    layout.authentication.isAuthenticated(function(json){
        layout.session.user = json.data;
        if (loginFun) loginFun();
    }.bind(this), function(){
        layout.authentication.loadLogin(this.node);
    });
};

MWF.xDesktop.getDefaultLayout = function(callback){
    MWF.UD.getPublicData("defaultLayout", function(json) {
        if (json) layout.defaultLayout = json;
        if (callback) callback();
    }.bind(this));
},
MWF.xDesktop.getUserLayout = function(callback){
    MWF.UD.getPublicData("forceLayout", function(json) {
        var forceStatus = null;
        if (json) forceStatus = json;
        MWF.UD.getDataJson("layout", function(json) {
            if (json) {
                layout.userLayout = json;
                if (forceStatus) layout.userLayout.apps = Object.merge(layout.userLayout.apps, forceStatus.apps);
                if (callback) callback();
            }else{
                MWF.UD.getPublicData("defaultLayout", function(json) {
                    if (json){
                        layout.userLayout = json;
                        if (forceStatus) layout.userLayout.apps = Object.merge(layout.userLayout.apps, forceStatus.apps);
                    }
                    if (callback) callback();
                }.bind(this));
            }
        }.bind(this));
    }.bind(this));
},

MWF.xDesktop.notice = function(type, where, content, target, offset, option){
    if (!where) where = { "x": "right", "y": "top" };
    if (!type) type = "ok";
    var noticeTarget = target || layout.desktop.desktopNode || document.body;

    var off = offset;
    if (!off){
        off = {
            x: 10,
            y: where.y.toString().toLowerCase()=="bottom" ? 10 : 10
        };
    }

    var options = {
        type: type,
        position: where,
        move: false,
        target: noticeTarget,
        offset: off,
        content: content
    };
    if( option && typeOf(option) === "object" ){
        options = Object.merge( options, option );
    }
    new mBox.Notice(options);
};
MWF.xDesktop.loadPortal =  function(portalId){
    layout.openApplication(null, "portal.Portal", {
        "portalId": portalId,
        "onAfterModulesLoad": function(){
            var layoutNode = $("layout");
            if (layoutNode) layoutNode.setStyles({
                "position": "absolute",
                "width": "100%",
                "z-index": 100,
                "top": "0px",
                "left": "0px"
            }).fade("out");
            var appContentNode = $("appContent");
            if (appContentNode) appContentNode.setStyles({
                "position": "absolute",
                "width": "100%",
                "top": "0px",
                "opacity": 0,
                "left": "0px"
            }).fade("in");
        }
    }, null, true);
};
MWF.name = {
    "cns": function(names){
        if( typeOf(names) !== "array" )return [];
        var n = [];
        names.each(function(v){
            n.push(this.cn(v));
        }.bind(this));
        return n;
    },
    "cn": function(name){
        if (!name) return "";
        var idx = name.indexOf("@");
        return (idx!==-1) ? name.substring(0, idx) : name;
    },
    "ou": function(name){
        if (!name) return "";
        var idx = name.indexOf("@");
        var lastIdx = name.lastIndexOf("@");
        if (idx===-1){
            return name;
        }else if (lastIdx===idx){
            return "";
        }else{
            return name.substring(idx+1, lastIdx);
        }
    },
    "flag": function(name){
        if (!name) return "";
        var lastIdx = name.lastIndexOf("@");
        if (lastIdx===-1){
            return "";
        }else{
            return name.substring(lastIdx+1, name.length);
        }
    },
    "type": function(name){
        if (!name) return "";
        var lastIdx = name.lastIndexOf("@");
        if (lastIdx===-1){
            return "";
        }else{
            return name.substring(lastIdx+1, name.length);
        }
    }
};
MWF.xDesktop.confirm = function(type, e, title, text, width, height, ok, cancel, callback, mask, style){
    MWF.require("MWF.xDesktop.Dialog", function(){
        var container = layout.desktop.node || $(document.body);
        var size = container.getSize();
        var x = 0;
        var y = 0;

        if (typeOf(e)=="element"){
            var position = e.getPosition(container);
            x = position.x;
            y = position.y;
        }else{
            if (Browser.name=="firefox"){
                x = parseFloat(e.event.clientX);
                y = parseFloat(e.event.clientY);
            }else{
                x = parseFloat(e.event.x);
                y = parseFloat(e.event.y);
            }

            if (e.target){
                var position = e.target.getPosition(container);
                x = position.x;
                y = position.y;
            }
            //    }
        }

        if (x+parseFloat(width)>size.x){
            x = x-parseFloat(width);
        }
        if (x<0) x = 0;
        if (y+parseFloat(height)>size.y){
            y = y-parseFloat(height);
        }
        if (y<0) y = 0;

        var ctext = "";
        var chtml = "";
        if (typeOf(text).toLowerCase()=="object"){
            ctext = text.text;
            chtml = text.html;
        }else{
            ctext = text;
        }
        var dlg = new MWF.xDesktop.Dialog({
            "title": title,
            "style": style || "o2",
            "top": y,
            "left": x-20,
            "fromTop":y,
            "fromLeft": x-20,
            "width": width,
            "height": height,
            "text": ctext,
            "html": chtml,
            "container": MWF.xDesktop.node,
            "maskNode": mask,
            "buttonList": [
                {
                    "type": "ok",
                    "text": MWF.LP.process.button.ok,
                    "action": ok
                },
                {
                    "type": "cancel",
                    "text": MWF.LP.process.button.cancel,
                    "action": cancel
                }
            ]
        });

        switch (type.toLowerCase()){
            case "success":
                dlg.content.setStyle("background-image", "url()");
                break;
            case "error":
                dlg.content.setStyle("background-image", "url()");
                break;
            case "info":
                dlg.content.setStyle("background-image", "url()");
                break;
            case "warn":
                dlg.content.setStyle("background-image", "url()");
                break;
            default:
            //dlg.content.setStyle("background-image", "");
        }
        dlg.show();
        if (callback) callback(dlg);
    }.bind(this));
};
MWF.xDesktop.getImageSrc = function( id ){
    if (layout.config.app_protocol=="auto"){
        layout.config.app_protocol = window.location.protocol;
    }

    var addressObj = layout.serviceAddressList["x_file_assemble_control"];
    if (addressObj){
        var address = layout.config.app_protocol+"//"+addressObj.host+((!addressObj.port || addressObj.port==80) ? "" : ":"+addressObj.port)+addressObj.context;
    }else{
        var host = layout.config.center.host || window.location.hostname;
        var port = layout.config.center.port;
        var address = layout.config.app_protocol+"//"+host+((port || port=="80") ? "" : ":"+port)+"/x_program_center";
    }
    var url = "/jaxrs/file/"+id+"/download/stream";
    return o2.filterUrl(address+url);
};
MWF.xDesktop.setImageSrc = function(){
    if( !event )return;
    var obj = event.srcElement ? event.srcElement : event.target;
    if( !obj )return;
    obj.onerror = null;
    var id = obj.get("data-id");
    if( id )obj.set("src" , MWF.xDesktop.getImageSrc(id) );
};
MWF.xDesktop.uploadImage = function( reference, referencetype, formData, file, success, failure ){
    this.action = new MWF.xDesktop.Actions.RestActions("/xDesktop/Actions/action.json", "x_file_assemble_control");
    this.action.invoke({
        "name": "uploadImage",
        "parameter": {"reference" : reference, "referencetype": referencetype},
        "data": formData,
        "file": file,
        "success": success,
        "failure": failure
    });
};
MWF.xDesktop.uploadImageByScale = function( reference, referencetype, scale, formData, file, success, failure ){
    this.action = new MWF.xDesktop.Actions.RestActions("/xDesktop/Actions/action.json", "x_file_assemble_control");
    this.action.invoke({
        "name": "uploadImageByScale",
        "parameter": {"reference" : reference, "referencetype": referencetype, "scale" : scale || 0},
        "data": formData,
        "file": file,
        "success": success,
        "failure": failure
    });
};
MWF.xDesktop.copyImage = function( reference, referencetype, attachmentId, scale, success, failure ){
    this.action = new MWF.xDesktop.Actions.RestActions("/xDesktop/Actions/action.json", "x_file_assemble_control");
    this.action.invoke({
        "name": "copyImage",
        "parameter": {"reference" : reference, "referencetype": referencetype, "attachmentId" : attachmentId, "scale":scale || 0 },
        "success": success,
        "failure": failure
    });
};
MWF.xDesktop.getPortalFileUr = function(id, app){
    var root = "x_portal_assemble_surface";
    var url = MWF.Actions.getHost(root)+"/"+root+MWF.Actions.get(root).action.actions.readFile.uri;
    url = url.replace("{flag}", id);
    url = url.replace("{applicationFlag}", app);
    return url
};
MWF.xDesktop.getProcessFileUr = function(id, app){
    var root = "x_processplatform_assemble_surface";
    var url = MWF.Actions.getHost(root)+"/"+root+MWF.Actions.get(root).action.actions.readFile.uri;
    url = url.replace("{flag}", id);
    url = url.replace("{applicationFlag}", app);
    return url
};
MWF.xDesktop.getCMSFileUr = function(id, app){
    var root = "x_cms_assemble_control";
    var url = MWF.Actions.getHost(root)+"/"+root+MWF.Actions.get(root).action.actions.readFile.uri;
    url = url.replace("{flag}", id);
    url = url.replace("{applicationFlag}", app);
    return url
};

MWF.xDesktop.getServiceAddress = function(config, callback){
    var error = function(){
        //MWF.xDesktop.notice("error", {"x": "right", "y": "top"}, "")
        var loadingNode = $("browser_loadding");
        var contentNode = $("appContent");
        ((loadingNode) ? loadingNode.getFirst() : contentNode).empty();
        var html= "<div style='width: 800px; color: #ffffff; margin: 30px auto'>" +
            "<div style='height: 40px;'>" +
            "   <div style='height: 40px; width: 40px; float: left; background: url(../x_desktop/img/error.png)'></div>" +
            "   <div style='margin-left: 50px; font-size: 20px; line-height: 40px;'>"+MWF.LP.desktop.notice.errorConnectCenter1+"</div>" +
            "</div><div style='margin-left: 0px;'>";
        if (typeOf(config.center)==="array"){
            config.center.each(function(center){
                var h = (center.host) ? center.host : window.location.hostname;
                var p = (center.port) ? ":"+center.port : "";
                var url = "http://"+h+p+"/x_program_center/jaxrs/echo";
                html+="<br><a style='margin-left: 50px; color: #e0e8d1; line-height: 30px;' href='"+url+"' target='_blank'>"+url+"</a>"
            });
        }else{
            var h = (config.center.host) ? config.center.host : window.location.hostname;
            var p = (config.center.port) ? ":"+config.center.port : "";
            var url = "http://"+h+p+"/x_program_center/jaxrs/echo";
            html+="<br><a style='margin-left: 50px; color: #e0e8d1; line-height: 30px;'href='"+url+"' target='_blank'>"+url+"</a>"
        }
        html+="</div><br><div style='margin-left: 50px; font-size: 20px'>"+MWF.LP.desktop.notice.errorConnectCenter2+"</div></div>";

        ((loadingNode) ? loadingNode.getFirst() : contentNode).set("html", html);
        if (!loadingNode && contentNode){
            contentNode.setStyle("background-color", "#666666");
        }
    };

    if (typeOf(config.center)==="object"){
        MWF.xDesktop.getServiceAddressConfigObject(config.center, callback, error);
    }else if (typeOf(config.center)==="array"){
        var center = null;
        //var center = MWF.xDesktop.chooseCenter(config);
        if (center){
            MWF.xDesktop.getServiceAddressConfigObject(center, callback, function(){
                MWF.xDesktop.getServiceAddressConfigArray(config, callback, error);
            }.bind(this));
        }else{
            MWF.xDesktop.getServiceAddressConfigArray(config, callback, error);
        }
    }
};
MWF.xDesktop.chooseCenter = function(config){
    var host = window.location.host;
    var center = null;
    for (var i=0; i<config.center.length; i++){
        var ct = config.center[i];
        if (!ct.host || (ct.host.toString().toLowerCase()===host.toString().toLowerCase())){
            center = ct;
            break;
        }
    }
    return center;
};
MWF.xDesktop.getServiceAddressConfigArray = function(config, callback, error) {
    var requests = [];
    config.center.each(function(center){
        requests.push(
            MWF.xDesktop.getServiceAddressConfigObject(center, function(serviceAddressList, center){

                requests.each(function(res){
                    if (res && res.res) if (res.res.isRunning()){res.res.cancel();}
                    if (res && res.actionWorker) res.actionWorker.terminate();
                });
                if (callback) callback(serviceAddressList, center);
            }.bind(this), function(){

                if (requests.length){
                    for (var i=0; i<requests.length; i++){
                        if (requests[i].res) if (requests[i].res.isRunning()) return "";
                        if (requests[i].actionWorker && requests[i].actionWorker.terminate) return "";
                    }
                }
                if (error) error();
            }.bind(this))
        );
    }.bind(this));
};
MWF.xDesktop.getServiceAddressConfigObject = function(center, callback, error){
    var centerConfig = center;
    if (!centerConfig) centerConfig = layout.config.center;
    var host = centerConfig.host || window.location.hostname;
    var port = centerConfig.port;
    var uri = "";

    if (layout.config.app_protocol=="auto"){
        layout.config.app_protocol = window.location.protocol;
    }

    if (!port || port=="80"){
        uri = layout.config.app_protocol+"//"+host+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
    }else{
        uri = layout.config.app_protocol+"//"+host+":"+port+"/x_program_center/jaxrs/distribute/assemble/source/{source}";
    }

    var currenthost = (layout.config.applicationServer && layout.config.applicationServer.host) ? layout.config.applicationServer.host : window.location.hostname;
    //var currenthost = window.location.hostname;
    uri = uri.replace(/{source}/g, currenthost);
    //var uri = "http://"+layout.config.center+"/x_program_center/jaxrs/distribute/assemble";

    try{
        return MWF.restful("get", uri, null, {
            "onSuccess": function(json){
                //this.serviceAddressList = json.data;
                //this.centerServer = center;
                var serviceAddressList = json.data;
                if (layout.config.proxyApplicationEnable){
                    Object.keys(serviceAddressList).forEach(function(k){
                        if (k!=="x_message_assemble_communicate") serviceAddressList[k].port = window.location.port;
                    })
                }
                if (callback) callback(serviceAddressList, center);
            }.bind(this),
            "onRequestFailure": function(xhr){
                if (error) error(xhr);
            }.bind(this),
            "onError": function(xhr){
                if (error) error(xhr);
            }.bind(this)
        });
    }catch(e){
        if (error) error();
        return null;
    }
};
MWF.xDesktop.$globalEvents = {};
MWF.xDesktop.addEvent = function(name, type, fn){
    if (!MWF.xDesktop.$globalEvents[name]) MWF.xDesktop.$globalEvents[name] = {};
    if (!MWF.xDesktop.$globalEvents[name][type]) MWF.xDesktop.$globalEvents[name][type] = [];
    MWF.xDesktop.$globalEvents[name][type].push(fn);
};

MWF.xDesktop.addEvents = function(name, o){
    if (!MWF.xDesktop.$globalEvents[name]) MWF.xDesktop.$globalEvents[name] = {};
    Object.each(o, function(fn, type){
        MWF.xDesktop.addEvent(name, type, fn);
    }.bind(this));
};

MWF.xDesktop.removeEvent = function(name, type, fn){
    if (!MWF.xDesktop.$globalEvents[name]) return true;
    if (!MWF.xDesktop.$globalEvents[name][type]) return true;
    MWF.xDesktop.$globalEvents[name][type].erase(fn);
};
MWF.xDesktop.removeEvents = function(name, type){
    if (!MWF.xDesktop.$globalEvents[name]) return true;
    if (!MWF.xDesktop.$globalEvents[name][type]) return true;
    MWF.xDesktop.$globalEvents[name][type] = [];
};

MWF.org = {
    parseOrgData: function(data, flat, simple){
        if (data.distinguishedName){
            var flag = data.distinguishedName.substr(data.distinguishedName.length-2, 2);
            switch (flag.toLowerCase()){
                case "@i":
                    return this.parseIdentityData(data, flat, simple);
                    break;
                case "@p":
                    return this.parsePersonData(data, simple);
                    break;
                case "@u":
                    return this.parseUnitData(data, simple);
                    break;
                case "@g":
                    return this.parseGroupData(data, simple);
                    break;
                case "@r":
                    return this.parseRoleData(data, simple);
                    break;
                case "@a":
                    return this.parseAttributeData(data, simple);
                    break;
                default:
                    return data;
            }
        }else{
            return data;
        }
    },
    parseIdentityData: function(data, flat, simple){
        if( simple ){
            var data = {
                "id": data.id,
                "name": data.name,
                "distinguishedName": data.distinguishedName,
                "unitLevelName" : data.unitLevelName,
                "person": data.person,
                "unit": data.unit,
                "unitName": data.unitName,
            };
            if( data.ignoreEmpower )rData.ignoreEmpower = true;
            if( data.ignoredEmpower )rData.ignoredEmpower = true;
            return data;
        }
        var rData = {
            "id": data.id,
            "name": data.name,
            "unique": data.unique,
            "distinguishedName": data.distinguishedName,
            // "dn": data.distinguishedName,
            "person": data.person,
            "unit": data.unit,
            "unitName": data.unitName,
            // "unitLevel": data.unitLevel,
            "unitLevelName": data.unitLevelName
        };

        if( data.personName )rData.personName = data.personName;
        if( data.personEmployee )rData.personEmployee = data.personEmployee;
        if( data.personUnique )rData.personUnique = data.personUnique;
        if( data.personDn )rData.personDn = data.personDn;

        if( data.ignoreEmpower )rData.ignoreEmpower = true;
        if( data.ignoredEmpower )rData.ignoredEmpower = true;

        if( !flat || !data.personDn || !data.personEmployee || !data.personUnique ){
            var woPerson = data.woPerson;
            if (!data.woPerson){
                //MWF.require("MWF.xDesktop.Actions.RestActions", null, false);
                //this.action = new MWF.xDesktop.Actions.RestActions("", "x_organization_assemble_control");
                //var uri = "/jaxrs/person/{flag}";
                //uri = uri.replace("{flag}", data.person);

                //this.action.invoke({"uri": uri, "success": function(json){
                //    woPerson = json.data;
                //}.bind(this), "async":false});
                MWF.Actions.get("x_organization_assemble_control").getPerson(data.person, function(json){
                    woPerson = json.data
                }, null, false);
            }
            rData.personName = woPerson.name;
            rData.personEmployee = woPerson.employee;
            rData.personUnique = woPerson.unique;
            rData.personDn = woPerson.distinguishedName;

            if (!flat){
                rData.woPerson = {
                    "id": woPerson.id,
                    "genderType": woPerson.genderType,
                    "name": woPerson.name,
                    "employee": woPerson.employee,
                    "unique": woPerson.unique,
                    "distinguishedName": woPerson.distinguishedName,
                    "dn": woPerson.distinguishedName,
                    "mail": woPerson.mail,
                    "weixin": woPerson.weixin,
                    "qq": woPerson.qq,
                    "mobile": woPerson.mobile,
                    "officePhone": woPerson.officePhone
                };
            }
        }
        return rData;
    },
    parsePersonData: function(data, simple){
        if( simple ){
            return {
                "id": data.id,
                "name": data.name,
                "employee": data.employee,
                "distinguishedName": data.distinguishedName,
            }
        }else{
            return {
                "id": data.id,
                "genderType": data.genderType,
                "name": data.name,
                "employee": data.employee,
                "unique": data.unique,
                "distinguishedName": data.distinguishedName,
                "dn": data.distinguishedName,
                "mail": data.mail,
                "weixin": data.weixin,
                "qq": data.qq,
                "mobile": data.mobile,
                "officePhone": data.officePhone
            }
        }
    },
    parseUnitData: function(data, simple){
        if( simple ){
            return {
                "id": data.id,
                "name": data.name,
                "distinguishedName": data.distinguishedName,
                "levelName": data.levelName
            }
        }else{
            return {
                "id": data.id,
                "name": data.name,
                "unique": data.unique,
                "distinguishedName": data.distinguishedName,
                "dn": data.distinguishedName,
                "typeList":data.typeList,
                "shortName": data.shortName,
                "level": data.level,
                "levelName": data.levelName
            }
        }
    },
    parseGroupData: function(data, simple){
        if( simple ){
            return {
                "id": data.id,
                "name": data.name,
                "distinguishedName": data.distinguishedName
            }
        }else{
            return {
                "id": data.id,
                "name": data.name,
                "unique": data.unique,
                "distinguishedName": data.distinguishedName,
                "dn": data.distinguishedName
            }
        }
    },
    parseRoleData: function(data, simple){
        if( simple ){
            return {
                "id": data.id,
                "name": data.name,
                "distinguishedName": data.distinguishedName
            }
        }else{
            return {
                "id": data.id,
                "name": data.name,
                "unique": data.unique,
                "distinguishedName": data.distinguishedName,
                "dn": data.distinguishedName
            }
        }
    },
    parseAttributeData: function(data, simple){
        if(simple){
            return {
                "id": data.id,
                "name": data.name,
                "distinguishedName": data.distinguishedName,
                "person": data.person,
                "attributeList": Array.clone(data.attributeList)
            }
        }else{
            return {
                "id": data.id,
                "description": data.description,
                "name": data.name,
                "unique": data.unique,
                "distinguishedName": data.distinguishedName,
                "dn": data.distinguishedName,
                "person": data.person,
                "attributeList": Array.clone(data.attributeList)
            }
        }
    }
};
//var lp = o2.session.path + "/lp/" + o2.language + ".js";
// var lp = "../x_desktop/js/base_lp_" + o2.language +((o2.session.isDebugger) ? "" : ".min")+ ".js";
// if (!o2.LP){
//     new Request({
//         "url": lp,
//         "method": "get"
//     }).send();
// }

o2.openWindow = function(url){
    var a = new Element("a", {
        "target": "_blank",
        "href": url
    });
    a.click();
    a.destroy();
}
